 
package com.zdkj.subway.rca.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.subway.rca.entity.ViewCkOperatorsRemitOnewayQr;
import com.zdkj.subway.rca.mapper.ViewCkOperatorsRemitOnewayQrMapper;
import com.zdkj.subway.rca.service.ViewCkOperatorsRemitOnewayQrService;
import com.zdkj.subway.rca.util.LocalDateConverter;
import com.zdkj.subway.rca.util.LocalDateTimeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * VIEW
 *
 * @author stw
 * @date 2020-12-16 13:56:53
 */
@Service
public class ViewCkOperatorsRemitOnewayQrServiceImpl extends ServiceImpl<ViewCkOperatorsRemitOnewayQrMapper, ViewCkOperatorsRemitOnewayQr> implements ViewCkOperatorsRemitOnewayQrService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ViewCkOperatorsRemitOnewayQrServiceImpl.class);
    @Override
    public List<ViewCkOperatorsRemitOnewayQr> listViewCkOperatorsRemitOnewayQr(String startDate, String endDate, String operators, String lineCode) {
        ViewCkOperatorsRemitOnewayQr viewCkOperatorsRemitOnewayQr = new ViewCkOperatorsRemitOnewayQr();
        viewCkOperatorsRemitOnewayQr.setBeginTime(LocalDate.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        viewCkOperatorsRemitOnewayQr.setEndTime(LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        viewCkOperatorsRemitOnewayQr.setOperators(operators);
        viewCkOperatorsRemitOnewayQr.setLineCode(lineCode);
        QueryWrapper<ViewCkOperatorsRemitOnewayQr> queryWrappers = Wrappers.query(viewCkOperatorsRemitOnewayQr);
        queryWrappers.orderByAsc("OPERATORS");
        queryWrappers.orderByAsc("CAST(LINE_CODE AS SIGNED)");
        List<ViewCkOperatorsRemitOnewayQr> list = this.list(queryWrappers);
        List<ViewCkOperatorsRemitOnewayQr> listNew = new ArrayList<>();

        String operatorsName = null;
        for(ViewCkOperatorsRemitOnewayQr obj : list){
            if(!obj.getOperatorsName().equals(operatorsName) && operatorsName != null){
                ViewCkOperatorsRemitOnewayQr sum = getSum(operatorsName, list);
                listNew.add(sum);
            }
            operatorsName = obj.getOperatorsName();
            listNew.add(obj);
        }
        if(list.size() > 0) { //最后一个运营商
            ViewCkOperatorsRemitOnewayQr sum = getSum(operatorsName, list);
            listNew.add(sum);
        }
        ViewCkOperatorsRemitOnewayQr sum = getSum("合计", list);
        sum.setLineName("--");
        listNew.add(sum);
        return listNew;
    }

    private ViewCkOperatorsRemitOnewayQr getSum(String operatorsName,List<ViewCkOperatorsRemitOnewayQr> list){
        ViewCkOperatorsRemitOnewayQr sumViewCkOperatorsRemitOnewayQr = new ViewCkOperatorsRemitOnewayQr();
        sumViewCkOperatorsRemitOnewayQr.setOperatorsName(operatorsName);
        sumViewCkOperatorsRemitOnewayQr.setLineName("小计");
        if("合计".equals(operatorsName)){
            sumViewCkOperatorsRemitOnewayQr.setOperators("合计");
        }
        BigDecimal paidinOnewaySum = new BigDecimal("0");
		BigDecimal waitDaily = new BigDecimal("0");
		BigDecimal waitSouvenir = new BigDecimal("0");
        BigDecimal waitQrCode = new BigDecimal("0");		
		BigDecimal waitFace = new BigDecimal("0");
        BigDecimal receivableOnewayReceivedClean = new BigDecimal("0");
		BigDecimal resultDaily = new BigDecimal("0");
        BigDecimal resultQrCode = new BigDecimal("0");
		BigDecimal resultSouvenir = new BigDecimal("0");
		BigDecimal resultFace = new BigDecimal("0");
        BigDecimal remitOnewayTicket = new BigDecimal("0");
		BigDecimal remitDaily = new BigDecimal("0");
        BigDecimal remitQrCode = new BigDecimal("0");
		BigDecimal remitSouvenir = new BigDecimal("0");
        BigDecimal remitSubtotal = new BigDecimal("0");
		BigDecimal remitFace = new BigDecimal("0");


        for(ViewCkOperatorsRemitOnewayQr  obj : list){
            if(operatorsName.equals("合计") || operatorsName.equals(obj.getOperatorsName())){
                paidinOnewaySum = paidinOnewaySum.add(obj.getPaidinOnewaySum());
				waitDaily = waitDaily.add(obj.getWaitDaily());
				waitSouvenir = waitSouvenir.add(obj.getCommemorativeTicket());
                waitQrCode = waitQrCode.add(obj.getWaitQrCode());	
				waitFace = waitFace.add(obj.getFaceTicketCcb());	
                receivableOnewayReceivedClean = receivableOnewayReceivedClean.add(obj.getReceivableOnewayReceivedClean());
				resultDaily = resultDaily.add(obj.getResultDaily());
				resultSouvenir = resultSouvenir.add(obj.getReceivableCommemorativeTicket());
                resultQrCode = resultQrCode.add(obj.getResultQrCode());
				resultFace = resultFace.add(obj.getReceivableFaceTicketCcb());
                remitOnewayTicket = remitOnewayTicket.add(obj.getRemitOnewayTicket());
				remitDaily = remitDaily.add(obj.getRemitDaily());
				remitSouvenir = remitSouvenir.add(obj.getRemitCommemorativeTicket());
                remitQrCode = remitQrCode.add(obj.getRemitQrCode());
				remitFace = remitFace.add(obj.getRemitFaceTicketCcb());
                remitSubtotal = remitSubtotal.add(obj.getRemitSubtotal());

            }
        }

        sumViewCkOperatorsRemitOnewayQr.setPaidinOnewaySum(paidinOnewaySum.setScale(2,BigDecimal.ROUND_HALF_UP));
		sumViewCkOperatorsRemitOnewayQr.setWaitDaily(waitDaily.setScale(2,BigDecimal.ROUND_HALF_UP));
		sumViewCkOperatorsRemitOnewayQr.setCommemorativeTicket(waitSouvenir.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkOperatorsRemitOnewayQr.setWaitQrCode(waitQrCode.setScale(2,BigDecimal.ROUND_HALF_UP));
		sumViewCkOperatorsRemitOnewayQr.setFaceTicketCcb(waitFace.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkOperatorsRemitOnewayQr.setReceivableOnewayReceivedClean(receivableOnewayReceivedClean.setScale(2,BigDecimal.ROUND_HALF_UP));
		sumViewCkOperatorsRemitOnewayQr.setResultDaily(resultDaily.setScale(2,BigDecimal.ROUND_HALF_UP));
		sumViewCkOperatorsRemitOnewayQr.setReceivableCommemorativeTicket(resultSouvenir.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkOperatorsRemitOnewayQr.setResultQrCode(resultQrCode.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkOperatorsRemitOnewayQr.setReceivableFaceTicketCcb(resultFace.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkOperatorsRemitOnewayQr.setRemitOnewayTicket(remitOnewayTicket.setScale(2,BigDecimal.ROUND_HALF_UP));
		sumViewCkOperatorsRemitOnewayQr.setRemitDaily(remitDaily.setScale(2,BigDecimal.ROUND_HALF_UP));
		sumViewCkOperatorsRemitOnewayQr.setRemitCommemorativeTicket(remitSouvenir.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkOperatorsRemitOnewayQr.setRemitQrCode(remitQrCode.setScale(2,BigDecimal.ROUND_HALF_UP));
		sumViewCkOperatorsRemitOnewayQr.setRemitFaceTicketCcb(remitFace.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkOperatorsRemitOnewayQr.setRemitSubtotal(remitSubtotal.setScale(2,BigDecimal.ROUND_HALF_UP));
        return sumViewCkOperatorsRemitOnewayQr;
    }

    @Override
    public void export(String startDate,String endDate,String operators,String lineCode,HttpServletResponse response) {

        List<ViewCkOperatorsRemitOnewayQr> records = listViewCkOperatorsRemitOnewayQr(startDate,endDate,operators,lineCode);
        InputStream excelTemplateIs = null;
        try {response.reset(); // 非常重要
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            final String fileName = URLEncoder.encode("运营商划账（单程票及二维码）", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");

            // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
            // {} 代表普通变量 {.} 代表是list的变量

            excelTemplateIs = this.getClass().getResourceAsStream("/static/excel/template/export/ViewCkOperatorsRemitOnewayQrExcelTemplate.xlsx");

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerConverter(new LocalDateTimeConverter()).registerConverter(new LocalDateConverter()).withTemplate(excelTemplateIs).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("运营商划账（单程票及二维码）").build();
            // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行，然后下面的数据往后移动。默认 是false，会直接使用下一行，如果没有则创建。
            // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了，所以慎用
            // 简单的说 如果你的模板有list,且list不是最后一行，下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
            // 如果数据量大 list不是最后一行 参照另一个
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
            excelWriter.fill(records, fillConfig, writeSheet);
            Map<String, Object> map = new HashMap<>();
            map.put("beginTime", startDate);
            map.put("endTime", endDate);
            excelWriter.fill(map, writeSheet);
            excelWriter.finish();

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("导出运营商划账（单程票及二维码）异常");
        } finally {
            if(excelTemplateIs != null){
                try {
                    excelTemplateIs.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }
}
